package com.mediastory.spsserver.api.service.impl;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.Ostermiller.util.Base64;
import com.mediastory.spsserver.api.domain.Content_v1_0;
import com.mediastory.spsserver.api.dao.ApiDao;
import com.mediastory.spsserver.api.service.ApiSvc;

@Service
@Component("ApiSvcImpl_v1_0")
@Transactional
public class ApiSvcImpl_v1_0 implements ApiSvc {
	
	@Autowired
	private MessageSourceAccessor messages;

	@Autowired
	@Qualifier("ApiDaoImpl_v1_0")
	ApiDao apiDao;
	
	public ApiSvcImpl_v1_0() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public List<Object> findbyListCategory(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		return (List<Object>)(apiDao.SelectListCategory(condition));
	}

	@Override
	public List<Object> findbyListInCont(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return (List<Object>) (apiDao.SelectListContent(condition));
	}
	
	@Override
	public List<Content_v1_0> findbyListInCont2(
			Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		
		List<Content_v1_0> contents = (List<Content_v1_0>) (apiDao.SelectListContent2(condition));
		Map<String, Object> rMap = new HashMap<String, Object>();
		for(Content_v1_0 content_v_1 : contents){
			rMap.put("idx", content_v_1.getIdx());

			List<String> imgUrls = (List<String>) apiDao.SelectListImgUrl(rMap);
			
			List<String> previewImgUrls = new Vector<String>();
			for(int i=0; i<imgUrls.size(); i++) {
				//previewImgUrls.add(String.valueOf(imgUrls.get(i)));
				previewImgUrls.add(String.valueOf(imgUrls.get(i)).replace("imgUrls=", "").replace("{", "").replace("}", ""));
			}
			content_v_1.setImgUrls(previewImgUrls);
		}
		return (List<Content_v1_0>) (contents);
	}
	
	@Override
	public Map<String, Object> findbyListPagingInCont(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("contents", (List<Object>) (apiDao.SelectListContent(condition)));
		resultMap.put("contentsCnt", (Integer) (apiDao.SelectListContTotalCnt(condition)));
		
		return resultMap;
	}
	
	@Override
	public List<Object> findbyListMainCont(
			Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return (List<Object>) (apiDao.SelectListMainCont(condition));
		
	}

	
	@Override
	public String findbyNoticeIsNew(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		String isNew = "N";
		Integer listCnt =(Integer)(apiDao.SelectListNoticeTotalCnt(condition));
		if(listCnt != null && listCnt > 0){
			isNew = "Y";
		}
		return isNew;
	}
	
	@Override
	public Object findbyNotice(Map<String, Object> condition) throws Exception {
		return apiDao.SelectNotice(condition);
	}
	
	@Override
	public Object findbyUrgencyNotice(Map<String, Object> condition) throws Exception {
		return apiDao.SelectUrgencyNotice(condition);
	}	
	
	@Override
	public List<Object> findbyNoticeList(Map<String, Object> condition) throws Exception {
		return apiDao.SelectNoticeList(condition);
	}
	
	
	@Override
	public Object findbyInfo(Map<String, Object> condition) throws Exception {
		return apiDao.SelectInfo(condition);
	}
	
	@Override
	public Map<String, Object> findbyVerMngr(Map<String, Object> condition) throws Exception {
		return apiDao.SelectVerMngr(condition);
	}
	
	@Override
	public Map<String, Object> findbyVerMngr2(Map<String, Object> condition) throws Exception {
		return apiDao.SelectVerMngr2(condition);
	}
	
	@Override
	public List<Object> findbyListAdvertising(Map<String, Object> condition) throws Exception {
		return apiDao.SelectListAdvertising(condition);
	}	
	
	@Override
	public List<Object> findbyListPayContAndroid(Map<String, Object> condition) throws Exception {
		return apiDao.SelectListPayContAndriod(condition);
	}	
	
	@Override
	public List<Object> findbyListPayContIos(Map<String, Object> condition) throws Exception {
		return apiDao.SelectListPayContIos(condition);
	}	
	
	@Override
	public List<Object> findbyListGuide(Map<String, Object> condition) throws Exception {
		return apiDao.SelectListGuide(condition);
	}	

	@Override
	public int addGcmDevice(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		
		//기존 Device Key 삭제. on 상태의 값이 누적되지 않도록 하기 위함.
		apiDao.deleteGcmDevice(condition);
		
		return apiDao.InsertGcmDevice(condition);
	}

	@Override
	public int removeGcmDevice(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		return apiDao.deleteGcmDevice(condition);
	}
	
	@Override
	public int addApnsDevice(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		
		//기존 Device Key 삭제. on 상태의 값이 누적되지 않도록 하기 위함.
		apiDao.deleteApnsDevice(condition);
		
		return apiDao.InsertApnsDevice(condition);
	}

	@Override
	public int removeApnsDevice(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		return apiDao.deleteApnsDevice(condition);
	}
	
	@Override
	public Integer addLogInfo(Map<String, Object> logInfo) throws Exception {
		// TODO Auto-generated method stub
		return apiDao.insertLogInfo(logInfo);
	}
	
	@Override
	public Integer addContent(Map<String, Object> contData) throws Exception {
		// TODO Auto-generated method stub
		Integer contIdx = 0;
		List<File> fileList = new Vector<File>();
		try {
			// 데이터 등록
			List<JSONObject> dataList = (List<JSONObject>)contData.get("dataList");
			
			Integer userIdx=1;	
			
			for(int i=0;i<dataList.size();i++){
				JSONObject data = JSONObject.fromObject(dataList.get(i));
				
				String cmd = (String)data.get("cmd");
				userIdx = (Integer)data.get("userIdx");
				if(cmd.equals("contInsert")){
					contIdx = apiDao.insertContent(data);
				}
			}
			
			
			//파일 업로드		
			
			MultipartFile cFile = null;
			String fileType = "";
			String fileData = "";
			long fileSize = 0;
			
			
			MultipartFile contFile1 = (MultipartFile) contData.get("contFile1");
			MultipartFile contFile2 = (MultipartFile) contData.get("contFile2");
			MultipartFile contFile3 = (MultipartFile) contData.get("contFile3");
			
			if(contFile1 != null){	
					cFile = contFile1;
					
					fileType = "mainImg";
					
					//파일의 크기가 0인 경우 넘긴다.(콘텐츠 URL로 넘긴경우 제외)
					if(cFile == null || cFile.getSize() == 0){
						//continue;
					}			
					
					fileData = "contentImg";
					fileSize = cFile.getSize();
					
					long time = Calendar.getInstance().getTimeInMillis();
					//String prefixNm = Base64.encode((URLEncoder.encode(content.getTitle(), "utf-8")+Long.toString(time))) + (1 + (int)(Math.random() * 100));
					String prefixNm = contIdx + "_" + userIdx + "_" + Long.toString(time) + "_" + (1 + (int)(Math.random() * 100));
					//업로드 경로
					String uploadDir = messages.getMessage("file.content.uploadDir") + userIdx + "/";
					//viewUrl
					String viewUrl = messages.getMessage("file.content.viewUrl")  + userIdx + "/";
					String fileNm = "";
					String url = "";					
					
					if(fileType.equals("mainImg")){
						//if(cFile != null && ! cFile.isEmpty() && cFile.getContentType().contains("image")){
							fileNm = prefixNm + "_mainImg."+(cFile.getOriginalFilename()).split("\\.")[1];
						//}
						fileData = "file1";
					}else{
						//continue;
					}
					
					
					File file = new File(uploadDir+fileNm);
					url = viewUrl+fileNm;
					
					if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
						new File(uploadDir).mkdirs();
					}
					cFile.transferTo(file);
					
					fileList.add(file);			
					
					Map<String, Object> contFile = new HashMap<String, Object>();
					contFile.put("contIdx", contIdx);
					contFile.put("fileUrl", url);
					contFile.put("fileSize", fileSize);
					contFile.put("fileType", fileType);
					contFile.put("fileData", fileData);
					contFile.put("createdId", userIdx);
					contFile.put("createdIp", "111");				
					apiDao.contFileinsert(contFile);
			
			}
			
			if(contFile2 != null){	
				cFile = contFile2;
				
				fileType = "mainImg";
				
				//파일의 크기가 0인 경우 넘긴다.(콘텐츠 URL로 넘긴경우 제외)
				if(cFile == null || cFile.getSize() == 0){
					//continue;
				}			
				
				fileData = "contentImg";
				fileSize = cFile.getSize();
				
				long time = Calendar.getInstance().getTimeInMillis();
				//String prefixNm = Base64.encode((URLEncoder.encode(content.getTitle(), "utf-8")+Long.toString(time))) + (1 + (int)(Math.random() * 100));
				String prefixNm = contIdx + "_" + userIdx + "_" + Long.toString(time) + "_" + (1 + (int)(Math.random() * 100));
				//업로드 경로
				String uploadDir = messages.getMessage("file.content.uploadDir") + userIdx + "/";
				//viewUrl
				String viewUrl = messages.getMessage("file.content.viewUrl")  + userIdx + "/";
				String fileNm = "";
				String url = "";					
				
				if(fileType.equals("mainImg")){
					//if(cFile != null && ! cFile.isEmpty() && cFile.getContentType().contains("image")){
						fileNm = prefixNm + "_mainImg."+(cFile.getOriginalFilename()).split("\\.")[1];
					//}
					fileData = "file2";
				}else{
					//continue;
				}
				
				
				File file = new File(uploadDir+fileNm);
				url = viewUrl+fileNm;
				
				if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
					new File(uploadDir).mkdirs();
				}
				cFile.transferTo(file);
				
				fileList.add(file);			
				
				Map<String, Object> contFile = new HashMap<String, Object>();
				contFile.put("contIdx", contIdx);
				contFile.put("fileUrl", url);
				contFile.put("fileSize", fileSize);
				contFile.put("fileType", fileType);
				contFile.put("fileData", fileData);
				contFile.put("createdId", userIdx);
				contFile.put("createdIp", "111");				
				apiDao.contFileinsert(contFile);
		
			}
			
			if(contFile3 != null){	
				cFile = contFile3;
				
				fileType = "mainImg";
				
				//파일의 크기가 0인 경우 넘긴다.(콘텐츠 URL로 넘긴경우 제외)
				if(cFile == null || cFile.getSize() == 0){
					//continue;
				}			
				
				fileData = "contentImg";
				fileSize = cFile.getSize();
				
				long time = Calendar.getInstance().getTimeInMillis();
				//String prefixNm = Base64.encode((URLEncoder.encode(content.getTitle(), "utf-8")+Long.toString(time))) + (1 + (int)(Math.random() * 100));
				String prefixNm = contIdx + "_" + userIdx + "_" + Long.toString(time) + "_" + (1 + (int)(Math.random() * 100));
				//업로드 경로
				String uploadDir = messages.getMessage("file.content.uploadDir") + userIdx + "/";
				//viewUrl
				String viewUrl = messages.getMessage("file.content.viewUrl")  + userIdx + "/";
				String fileNm = "";
				String url = "";					
				
				if(fileType.equals("mainImg")){
					//if(cFile != null && ! cFile.isEmpty() && cFile.getContentType().contains("image")){
						fileNm = prefixNm + "_mainImg."+(cFile.getOriginalFilename()).split("\\.")[1];
					//}
					fileData = "file3";
				}else{
					//continue;
				}
				
				
				File file = new File(uploadDir+fileNm);
				url = viewUrl+fileNm;
				
				if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
					new File(uploadDir).mkdirs();
				}
				cFile.transferTo(file);
				
				fileList.add(file);		
				
				Map<String, Object> contFile = new HashMap<String, Object>();
				contFile.put("contIdx", contIdx);
				contFile.put("fileUrl", url);
				contFile.put("fileSize", fileSize);
				contFile.put("fileType", fileType);
				contFile.put("fileData", fileData);
				contFile.put("createdId", userIdx);
				contFile.put("createdIp", "111");				
				apiDao.contFileinsert(contFile);
		
			}
			
			/*
			List<MultipartFile> contFiles = new ArrayList<MultipartFile>();
			contFiles = (List<MultipartFile>) contData.get("contFiles");
			//MultipartFile[] contFiles = (MultipartFile[]) contData.get("contFiles");
			
			if(contFiles != null){
				
				for(int i = 0;i<contFiles.size();i++){
					cFile = contFiles.get(i);
					
					fileType = "mainImg";
					
					//파일의 크기가 0인 경우 넘긴다.(콘텐츠 URL로 넘긴경우 제외)
					if(cFile == null || cFile.getSize() == 0){
						continue;
					}			
					
					fileData = "contentImg";
					fileSize = cFile.getSize();
					
					long time = Calendar.getInstance().getTimeInMillis();
					//String prefixNm = Base64.encode((URLEncoder.encode(content.getTitle(), "utf-8")+Long.toString(time))) + (1 + (int)(Math.random() * 100));
					String prefixNm = contIdx + "_" + userIdx + "_" + Long.toString(time) + "_" + (1 + (int)(Math.random() * 100));
					//업로드 경로
					String uploadDir = messages.getMessage("file.content.uploadDir") + userIdx + "/";
					//viewUrl
					String viewUrl = messages.getMessage("file.content.viewUrl")  + userIdx + "/";
					String fileNm = "";
					String url = "";					
					
					if(fileType.equals("mainImg")){
						if(cFile != null && ! cFile.isEmpty() && cFile.getContentType().contains("image")){
							fileNm = prefixNm + "_mainImg."+(cFile.getOriginalFilename()).split("\\.")[1];
						}
						fileData = "" + i;
					}else{
						continue;
					}
					
					
					File file = new File(uploadDir+fileNm);
					url = viewUrl+fileNm;
					
					if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
						new File(uploadDir).mkdirs();
					}
					cFile.transferTo(file);
					
					fileList.add(file);
					
					
					Map<String, Object> contFile = new HashMap<String, Object>();
					contFile.put("contIdx", contIdx);
					contFile.put("fileUrl", url);
					contFile.put("fileSize", fileSize);
					contFile.put("fileType", fileType);
					contFile.put("fileData", fileData);
					contFile.put("createdId", userIdx);
					contFile.put("createdIp", "111");				
					apiDao.contFileinsert(contFile);
				}
				
			}
			*/
			 	
		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			for (File file : fileList) {
				file.delete();
			}
			
			throw e;
		}
		
		return contIdx;
	}
	
	@Override
	public int updateContent(Map<String, Object> contData) throws Exception {
		// TODO Auto-generated method stub
		
		// 데이터 등록
		List<JSONObject> dataList = (List<JSONObject>)contData.get("dataList");
		
		for(int i=0;i<dataList.size();i++){
			JSONObject data = JSONObject.fromObject(dataList.get(i));
			
			String cmd = (String)data.get("cmd");
			if(cmd.equals("contModify")){
				apiDao.updateContent(data);
			}else if(cmd.equals("contEnd")){
				apiDao.updateContent(data);
			}else if(cmd.equals("contDel")){
				apiDao.deleteContent(data);
			}
		}
		
		return 0;
	}
	
	@Override
	public Integer addComment(Map<String, Object> contData) throws Exception {
		// TODO Auto-generated method stub
		Integer contIdx = 0;
		
		// 데이터 등록
		List<JSONObject> dataList = (List<JSONObject>)contData.get("dataList");			
		Integer userIdx=1;				
		for(int i=0;i<dataList.size();i++){
			JSONObject data = JSONObject.fromObject(dataList.get(i));
			
			String cmd = (String)data.get("cmd");
			userIdx = (Integer)data.get("userIdx");
			if(cmd.equals("commentInsert")){
				contIdx = apiDao.insertComment(data);
			}
		}
		
		return contIdx;
	}
	
	@Override
	public int updateComment(Map<String, Object> contData) throws Exception {
		// TODO Auto-generated method stub
		
		// 데이터 등록
		List<JSONObject> dataList = (List<JSONObject>)contData.get("dataList");
		
		for(int i=0;i<dataList.size();i++){
			JSONObject data = JSONObject.fromObject(dataList.get(i));
			
			String cmd = (String)data.get("cmd");
			if(cmd.equals("commentDel")){
				apiDao.deleteComment(data);
			}
		}
		
		return 0;
	}
	
	@Override
	public List<Object> findbyListInComment(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return (List<Object>) (apiDao.SelectListComment(condition));
	}
	
	@Override
	@Transactional(value="transactionManagerLogData")
	public int addLogging(Map<String, Object> logData) throws Exception {
		// TODO Auto-generated method stub
		
		//log info 등록
		Map<String, Object> logInfo = (Map<String, Object>)logData.get("logInfo");
		Integer logInfoIdx = apiDao.insertLogInfo(logInfo);
		
		//log 데이터 등록
		List<JSONObject> dataList = (List<JSONObject>)logData.get("dataList");
		
		for(int i=0;i<dataList.size();i++){
			JSONObject data = JSONObject.fromObject(dataList.get(i));
			data.put("logInfoIdx", logInfoIdx);
			
			String cmd = (String)data.get("cmd");
			if(cmd.equals("appLifeCycle")){
				apiDao.insertAppLifeCycle(data);
			}else if(cmd.equals("downCont")){
				apiDao.insertDownCont(data);
			}else if(cmd.equals("confirmPush")){
				apiDao.insertConfirmPush(data);
			}else if(cmd.equals("confirmNotice")){
				apiDao.insertConfirmNoti(data);
			}else if(cmd.equals("appUpdate")){
				apiDao.insertAppUpdate(data);
			}else if(cmd.equals("setupPush")){
				apiDao.insertSetupPush(data);
			}else if(cmd.equals("error")){
				apiDao.insertError(data);
			}else if(cmd.equals("detailedEvent")){
				apiDao.insertDetailedEvent(data);
			}else if(cmd.equals("adClick")){
				apiDao.insertAdClick(data);
			}else if(cmd.equals("adRolling")){
				apiDao.insertAdRolling(data);
			}else if(cmd.equals("viewCont")){
				apiDao.insertViewCont(data);
			}else if(cmd.equals("detailedCont")){
				apiDao.insertDetailedCont(data);
			}else if(cmd.equals("view")){
				apiDao.insertView(data);
			}else if(cmd.equals("viewLog")){
				Integer logViewlogIdx = apiDao.insertViewlog(data);
				List<JSONObject> logDataList = (List<JSONObject>)data.get("logData");
				for(int j=0;j<logDataList.size();j++){
					JSONObject viewLogData = JSONObject.fromObject(logDataList.get(j));
					viewLogData.put("logViewlogIdx", logViewlogIdx);
					viewLogData.put("logInfoIdx", logInfoIdx);
					apiDao.insertViewlogData(viewLogData);
				}
			}
		}
		
		return 0;
	}
	
	@Override
	@Transactional(value="transactionManagerPurchaseData")
	public int addPurchaseData(Map<String, Object> logData) throws Exception {
		// TODO Auto-generated method stub
		
		//log info 등록
		Map<String, Object> logInfo = (Map<String, Object>)logData.get("logInfo");
		Integer logInfoIdx = apiDao.insertPurLogInfo(logInfo);
		
		//log 데이터 등록
		List<JSONObject> dataList = (List<JSONObject>)logData.get("dataList");
		
		//OS 구분
		String osGubun = (String)logData.get("osGubun");
		
		for(int i=0;i<dataList.size();i++){
			JSONObject data = JSONObject.fromObject(dataList.get(i));
			data.put("logInfoIdx", logInfoIdx);
			
			if(osGubun.equals("ios")) {
				apiDao.insertIosPurchaseData(data);
			} else if (osGubun.equals("android")) {
				apiDao.insertAndroidPurchaseData(data);
			}
			
		}
		
		return 0;
	}
	
	@Override
	public Integer findbyAppSeqId() throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> appSeqId =  new HashMap<String, Object>();
		return (Integer) (apiDao.SelectAppSeqId(appSeqId));
	}
}